#include <iostream>
#include <cmath> 
class Function {
public:
    virtual double operator () (double x) = 0;
    
    virtual double d(double x) = 0;
};

class NewtonSolver {
protected:
    Function &F;

public:
    NewtonSolver(Function & F) : F(F) {}

    double solve(double x0) {
        const int max_iterations = 5;
        const double tolerance = 1e-9;

        double x_current = x0;

        for (int i = 0; i < max_iterations; ++i) {
            double fx = F(x_current);
            double fdx = F.d(x_current);

            // 检查数值稳定性：
            // 1. 函数值或导数是否为有限数，防止 Inf 或 NaN
            // 2. 导数是否接近于零，防止有除以零的错误
            if (!std::isfinite(fx) || !std::isfinite(fdx) || std::fabs(fdx) < 1e-15) {
                // 如果不稳定，提前退出，返回当前最接近的解
                std::cout << "Warning: Iteration stopped due to numerical instability." << std::endl;
                return x_current;
            }

            double x_next = x_current - fx / fdx;

            // 混合收敛判据：
            // 结合了绝对误差和相对误差，确保在根接近0时也能正常工作
            if (std::fabs(x_next - x_current) <= tolerance * std::fmax(1.0, std::fabs(x_next))) {
                // 如果满足收敛条件，直接返回下一个更精确的解
                return x_next;
            }

            x_current = x_next;
        }

        // 达到最大迭代次数但未收敛到指定精度
        std::cout << "Warning: Reached max iterations (" << max_iterations << ") without meeting tolerance." << std::endl;
        return x_current;
    }
};

